<template>
  <div class="notice-management">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span class="title">预约须知管理</span>
          <el-button type="primary" @click="showAddDialog" :icon="Plus">
            新增须知
          </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入须知内容关键词"
          style="width: 300px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 表格区域 -->
      <el-table
        :data="filteredNoticeList"
        v-loading="loading"
        stripe
        style="width: 100%"
        class="notice-table"
      >
        <el-table-column prop="noticeId" label="ID" width="80" />
        <el-table-column prop="noticeName" label="须知内容" min-width="400">
          <template #default="{ row }">
            <div class="notice-content">
              {{ truncateText(row.noticeName, 100) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="dateTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.dateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="showDetailDialog(row)"
              :icon="View"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增须知对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增预约须知"
      width="80%"
      :before-close="handleAddDialogClose"
    >
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="100px">
        <el-form-item label="须知内容" prop="noticeName">
          <div class="rich-editor-container">
            <div ref="editorRef" class="editor"></div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAdd" :loading="addLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="预约须知详情"
      width="80%"
    >
      <div class="detail-content">
        <div class="detail-item">
          <label>须知ID：</label>
          <span>{{ currentNotice.noticeId }}</span>
        </div>
        <div class="detail-item">
          <label>创建时间：</label>
          <span>{{ formatDateTime(currentNotice.dateTime) }}</span>
        </div>
        <div class="detail-item">
          <label>须知内容：</label>
          <div class="notice-detail-content" v-html="currentNotice.noticeName"></div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Search, View } from '@element-plus/icons-vue'
import { dataRead, dataWrite } from '@/Utils/Http'
import Quill from 'quill'
import 'quill/dist/quill.snow.css'

// 响应式数据
const loading = ref(false)
const addLoading = ref(false)
const noticeList = ref([])
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框控制
const addDialogVisible = ref(false)
const detailDialogVisible = ref(false)

// 表单相关
const addFormRef = ref<FormInstance>()
const addForm = reactive({
  noticeName: ''
})

const addRules: FormRules = {
  noticeName: [
    { 
      required: true, 
      message: '请输入须知内容', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (!value || value.trim() === '' || value === '<p><br></p>') {
          callback(new Error('请输入须知内容'))
        } else {
          callback()
        }
      }
    }
  ]
}

// 当前查看的须知
const currentNotice = ref({
  noticeId: 0,
  noticeName: '',
  dateTime: ''
})

// 富文本编辑器
let quillEditor: Quill | null = null
const editorRef = ref()

// 计算属性 - 过滤后的列表
const filteredNoticeList = computed(() => {
  if (!searchKeyword.value) {
    return noticeList.value
  }
  return noticeList.value.filter((item: any) => {
    // 去除HTML标签后进行搜索
    const plainText = stripHtmlTags(item.noticeName)
    return plainText.toLowerCase().includes(searchKeyword.value.toLowerCase())
  })
})

// 方法
const loadNoticeList = async () => {
  try {
    loading.value = true
    const response = await dataRead.get('/MCI/NoticeQuery')
    if (response.data.code === 200) {
      noticeList.value = response.data.data || []
      total.value = noticeList.value.length
    } else {
      ElMessage.error('获取预约须知列表失败')
    }
  } catch (error) {
    console.error('获取预约须知列表失败:', error)
    ElMessage.error('获取预约须知列表失败')
  } finally {
    loading.value = false
  }
}

const showAddDialog = async () => {
  addDialogVisible.value = true
  await nextTick()
  initRichEditor()
}

const initRichEditor = () => {
  if (editorRef.value && !quillEditor) {
    quillEditor = new Quill(editorRef.value, {
      theme: 'snow',
      modules: {
        toolbar: [
          ['bold', 'italic', 'underline', 'strike'],
          ['blockquote', 'code-block'],
          [{ 'header': 1 }, { 'header': 2 }],
          [{ 'list': 'ordered'}, { 'list': 'bullet' }],
          [{ 'script': 'sub'}, { 'script': 'super' }],
          [{ 'indent': '-1'}, { 'indent': '+1' }],
          [{ 'direction': 'rtl' }],
          [{ 'size': ['small', false, 'large', 'huge'] }],
          [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
          [{ 'color': [] }, { 'background': [] }],
          [{ 'font': [] }],
          [{ 'align': [] }],
          ['clean'],
          ['link', 'image']
        ]
      }
    })
    
    // 监听编辑器内容变化，实时更新表单数据
    quillEditor.on('text-change', () => {
      const content = quillEditor.root.innerHTML
      addForm.noticeName = content
    })
  }
}

const handleAdd = async () => {
  if (!addFormRef.value) return
  
  try {
    if (!quillEditor) {
      ElMessage.error('富文本编辑器未初始化')
      return
    }

    // 确保表单数据是最新的
    const content = quillEditor.root.innerHTML
    addForm.noticeName = content
    
    // 验证表单
    await addFormRef.value.validate()
    
    addLoading.value = true
    
    const response = await dataWrite.post('/MCI/AddNotice', {
      noticeName: content
    })

    if (response.data.code === 300) {
      ElMessage.success('新增预约须知成功')
      addDialogVisible.value = false
      resetAddForm()
      loadNoticeList()
    } else {
      ElMessage.error(response.data.message || '新增预约须知失败')
    }
  } catch (error) {
    console.error('新增预约须知失败:', error)
    ElMessage.error('新增预约须知失败')
  } finally {
    addLoading.value = false
  }
}

const resetAddForm = () => {
  addForm.noticeName = ''
  if (quillEditor) {
    quillEditor.setContents([])
  }
}

const handleAddDialogClose = () => {
  resetAddForm()
  addDialogVisible.value = false
}

const showDetailDialog = (row: any) => {
  currentNotice.value = { ...row }
  detailDialogVisible.value = true
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 去除HTML标签的函数
const stripHtmlTags = (html: string) => {
  if (!html) return ''
  // 创建一个临时的div元素来解析HTML
  const tempDiv = document.createElement('div')
  tempDiv.innerHTML = html
  return tempDiv.textContent || tempDiv.innerText || ''
}

const truncateText = (text: string, maxLength: number) => {
  if (!text) return ''
  // 先去除HTML标签，再截取文本
  const plainText = stripHtmlTags(text)
  if (plainText.length <= maxLength) return plainText
  return plainText.substring(0, maxLength) + '...'
}

const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 生命周期
onMounted(() => {
  loadNoticeList()
})
</script>

<style scoped>
.notice-management {
  padding: 20px;
}

.main-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: #1e3a8a;
}

.search-area {
  margin-bottom: 20px;
}

.notice-table {
  margin-bottom: 20px;
}

.notice-content {
  line-height: 1.5;
  color: #606266;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.rich-editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.editor {
  height: 300px;
}

.detail-content {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.detail-item label {
  font-weight: 600;
  color: #1e3a8a;
  min-width: 100px;
  margin-right: 10px;
}

.notice-detail-content {
  flex: 1;
  line-height: 1.6;
  color: #606266;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 15px;
  background-color: #fafafa;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 富文本编辑器样式调整 */
:deep(.ql-editor) {
  min-height: 250px;
}

:deep(.ql-toolbar) {
  border-top: 1px solid #dcdfe6;
  border-left: 1px solid #dcdfe6;
  border-right: 1px solid #dcdfe6;
}

:deep(.ql-container) {
  border-bottom: 1px solid #dcdfe6;
  border-left: 1px solid #dcdfe6;
  border-right: 1px solid #dcdfe6;
}
</style>
